package com.logic.landseaserver.common.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.logic.common.exception.BusinessException;

import net.sf.json.JSONObject;

@Service
public class WeBankServiceUtil {
	private static WeBankUtil instance = WeBankUtil.getInstance();
	private static WeBankQRUtil QRinstance = WeBankQRUtil.getInstance();
	private static String ROOT_URL;
	private static String WEBANK_PAY_QR_URL = "/api/acq/server/wepay/syncPaymentInfo";
	
	private static Logger logger = LoggerFactory.getLogger(WeBankServiceUtil.class);
	//微信支付二维码
	public static String getWeBankPayQR(Map<String,String> param,String ticket) throws Exception {
		String result = null ;
		if(true){
			List<String> values = new ArrayList<String>();
			
			JSONObject json = JSONObject.fromObject(param);
			String nonceStr = WeBankQRUtil.getNonceStr();
			values.add(QRinstance.getApp_id());
			values.add(QRinstance.getVersion());
			values.add(nonceStr);
			values.add(json.toString());
			
			String sign = WeBankQRUtil.sign(values, ticket);
			
			logger.info("二维码body:   " +json.toString());
			
			String url = QRinstance.getPay_url()+"?app_id="+QRinstance.getApp_id()+"&version=1.0.0&nonce="+nonceStr+"&sign="+sign;
	        String apiresult = WeBankQRUtil.SSLPostRequest(url, json.toString());
	        logger.info("二维码url:  " + url);
	        JSONObject resultjson = JSONObject.fromObject(apiresult);
	        logger.info("二维码返回值:  "+resultjson.toString());
	        if("0".equals(resultjson.getString("code"))){
	        	String payurl = resultjson.getString("qrCode");
	        	return payurl;
	        }else{
	        	logger.info("微众\"收单\"下单失败"+resultjson.getString("msg"));
	        	throw new Exception("微众收单下单失败"+resultjson.getString("msg"));
	        }
		}
		return result;
	}
	
	
    /**
     * 
     * [简要描述]：收银台调出支付页面</br>
     * [详细描述]：</br>
     * [作者]：Aaron(2017-08-01)</br>
     *
     * @param param
     * @param ticket 验签
     * @param accessToken 为获取nonce Ticket用
     * @return
     * @throws Exception
     *
     */
    public static String syncPaymentInfo(Map<String, String> param, String ticket, String accessToken)
        throws Exception
    {
        String type = "SYNC_PAYMENT_INFO";
        String result = null;
        if (validateParam(param))
        {
            List<String> values = new ArrayList<String>();
            List<String> onceValues = new ArrayList<String>();
            
            JSONObject json = JSONObject.fromObject(param);
            String nonceStr = WeBankUtil.getNonceStr();
            values.add(instance.getApp_id());
            values.add(instance.getVersion());
            values.add(nonceStr);
            values.add(type);
            values.add(json.toString());
            
            onceValues.add(instance.getApp_id());
            onceValues.add(param.get("userId"));
            onceValues.add(nonceStr);
            onceValues.add(instance.getVersion());
            
            String sign = WeBankUtil.sign(values, ticket);
            
            logger.info("支付信息同步接口请求|" + json.toString());
            
            ROOT_URL = instance.getRoot_url();
            String url = ROOT_URL + WEBANK_PAY_QR_URL + "?app_id=" + instance.getApp_id() + "&version=1.0.0&nonce="
                + nonceStr + "&sign=" + sign + "&type=SYNC_PAYMENT_INFO";
            
            logger.info("支付信息同步接口|URL=" + url);
            
            String apiresult = WeBankUtil.SSLPostRequest(url, json.toString());
            JSONObject resultjson = JSONObject.fromObject(apiresult);
            
            logger.info("支付信息同步接口响应|" + resultjson.toString());
            
            if (resultjson.containsKey("code"))
            {
                if ("0".equals(resultjson.getString("code")))
                {
                    String jsonDataStr = resultjson.getString("jsonData").replace("\\", ",");
                    JSONObject jsonData = JSONObject.fromObject(jsonDataStr);
                    if ("0".equals(jsonData.getString("retCode")))
                    { 
                        // 微众下订单成功
                        // 获取nonceTicket
                        String onceTicket = instance.getNonceTicket(param.get("userId"), accessToken);
                        String onceSign = WeBankUtil.sign(onceValues, onceTicket);
                        StringBuffer payurl = new StringBuffer(instance.getPc_QR_url());
                        payurl.append(param.get("userId") + "/");
                        payurl.append(nonceStr + "/");
                        payurl.append(onceSign + "/");
                        payurl.append(param.get("orderNo") + "/");
                        // payurl.append("02/");
                        payurl.append(instance.getApp_id());
                        return payurl.toString();
                    }
                    else
                    {
                        logger.info("微众下单失败！");
                        throw new Exception("微众下单失败！");
                    }
                }
                else
                {
                    logger.info("支付信息同步接口调用失败！");
                    throw new Exception("支付信息同步接口调用失败！");
                }
            }
        }
        return result;
    }
		
		
	private static boolean validateParam(Map param) throws BusinessException {
		if(!param.containsKey("webankAppId")){
			throw new BusinessException("没有webankAppId");
		}
		if(!param.containsKey("orderNo")){
			throw new BusinessException("没有订单编号");
		}
		if(!param.containsKey("amount")){
			throw new BusinessException("没有交易金额");
		}
		if(!param.containsKey("reqTime")){
			throw new BusinessException("没有请求时间");
		}
		if(!param.containsKey("merchantId")){
			throw new BusinessException("没有商户编号");
		}
		if(!param.containsKey("merchantName")){
			throw new BusinessException("没有商户名称");
		}
		if(!param.containsKey("userId")){
			throw new BusinessException("没有用户在合作方的userid");
		}
		if(!param.containsKey("redirectUrl")){
			throw new BusinessException("没有支付成功后的跳转 URL");
		}
		if(!param.containsKey("goodsName")){
			throw new BusinessException("没有商品名");
		}
		return true;
	}

	//收单账单查询
	public static String getWeBankQRPayCheck(Map<String, String> param, String ticket) throws Exception {
		List<String> values = new ArrayList<String>();
		
		JSONObject json = JSONObject.fromObject(param);
		String nonceStr = WeBankQRUtil.getNonceStr();
		values.add(QRinstance.getApp_id());
		values.add(QRinstance.getVersion());
		values.add(nonceStr);
		values.add(json.toString());
		String sign = WeBankQRUtil.sign(values, ticket);
		
	    StringBuilder urlBuffer = new StringBuilder();
        urlBuffer.append(StringTools.splitJointPath(QRinstance.getRoot_url(), QRinstance.getPay_check_url()));
        urlBuffer.append("?app_id=");
        urlBuffer.append(QRinstance.getApp_id());
        urlBuffer.append("&version=1.0.0&nonce=");
        urlBuffer.append(nonceStr);
        urlBuffer.append("&sign=");
        urlBuffer.append(sign);
	        
	    String url = urlBuffer.toString();
	        
	    logger.info("getWeBankQRPayCheck|查询订单开始|Url=" + url);
		
        String apiresult = WeBankQRUtil.SSLPostRequest(url, json.toString());
		return apiresult;
	}
	
	//收银台账单查询
	public static String getWeBankPayCheck(Map<String, String> param, String ticket) throws Exception {
		List<String> values = new ArrayList<String>();
		JSONObject json = JSONObject.fromObject(param);
		String nonceStr = WeBankQRUtil.getNonceStr();
		values.add(instance.getApp_id());
		values.add(instance.getVersion());
		values.add(nonceStr);
		values.add(json.toString());
		String sign = WeBankUtil.sign(values, ticket);
		logger.info("getWeBankPayCheck|查询订单开始|" + param);
		StringBuilder urlBuffer = new StringBuilder();
		urlBuffer.append(StringTools.splitJointPath(instance.getRoot_url(), instance.getPay_check_url()));
		urlBuffer.append("?app_id=");
		urlBuffer.append(instance.getApp_id());
		urlBuffer.append("&version=1.0.0&type=QUERY_TRANSACTION_RESULT&nonce=");
		urlBuffer.append(nonceStr);
		urlBuffer.append("&sign=");
		urlBuffer.append(sign);
		
		String url = urlBuffer.toString();
		
		logger.info("getWeBankPayCheck|查询订单开始|Url=" + url);
		
        String apiresult = WeBankUtil.SSLPostRequest(url, json.toString());
		return apiresult;
	}

}

